//
//  YFMomentModel.m
//  CoollangTennisBall
//
//  Created by Coollang on 2017/9/18.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "YFMomentModel.h"
#import "NSString+Extension.h"


@implementation YFMomentModel

+ (NSDictionary *)defaultPropertyValues {
    return @{
             @"userName":@"",
             @"icon":@"",
             @"userID":@"",
             @"topicID":@"",
             @"text":@"",
             @"longitude":@0,
             @"latitude":@0,
             @"createTime":@"",
             @"isLike":@0,
             @"isHandpicked":@"0",
             @"address":@"",
             @"images":@[],
             @"likeList":@[],
             @"responseList":@[],
             };
}

+ (NSArray<NSString *> *)ignoredProperties {
    return @[
             @"isMyMoment",
             @"isNeedShowMoreBtn",
             @"singleImageSize",
             @"showMoreSate",
             @"normalCellHeight",
             @"showMoreCellHeight",
             @"textLabelHeight",
             @"imagesHeight",
             @"timeAdressHeight",
             @"likeHeight",
             @"commentHeigh",
             @"likesString",
             ];
}

+ (RLMResults *)getMomemnts {
    // 获取所有的帖子模型
    RLMResults *resluts = [YFMomentModel allObjects];
    return resluts;
}

+ (void)addOrUpadteMoments:(NSArray <YFMomentModel *>*)moments {
    // 添加和更新帖子模型
    [[RLMRealm defaultRealm] beginWriteTransaction];
    [[RLMRealm defaultRealm] addOrUpdateObjectsFromArray:moments];
    [[RLMRealm defaultRealm] commitWriteTransaction];
}

- (void)parseMomentModelWithDict:(NSDictionary *)dict {
    
    self.userName = [NSString checkIfNullWithString:dict[@"UserName"]];
    self.icon = [NSString checkIfNullWithString:dict[@"Icon"]];
    self.userID = [NSString checkIfNullWithString:dict[@"UserID"]];
    self.topicID = [NSString checkIfNullWithString:dict[@"ID"]];
    self.text = [NSString checkIfNullWithString:dict[@"Text"]];
    NSString *position = [NSString checkIfNullWithString:dict[@"Position"]];
    self.longitude = [position componentsSeparatedByString:@","].firstObject.doubleValue;
    self.latitude = [position componentsSeparatedByString:@","].lastObject.doubleValue;
    self.createTime = [NSString checkIfNullWithString:dict[@"CreateTime"]];
    self.isLike = [NSString checkIfNullWithString:dict[@"IsLiked"]].boolValue;
    
    if ([dict.allKeys containsObject:@"Feature"]) {
        self.isHandpicked = [[NSString checkIfNullWithString:dict[@"Feature"]] boolValue];
    }
    // 图片
    for (NSString *imageUrl in dict[@"ImgList"]) {
        [self.images addObject:[YFMomentImageModel momentImageModelWithUrl:imageUrl]];
    }
    // 点赞
    [self.likeList addObjects:[NSArray modelArrayWithClass:[YFMomentsPersonModel class] json:dict[@"LikeList"]]];
    // 评论
    for (NSDictionary *jsonDict in dict[@"ResponseList"]) {
        YFMomentResponseModel *responseModel = [[YFMomentResponseModel alloc] init];
        [responseModel parseMomentResponseModelWithDict:jsonDict withmomentModel:self];
        [self.responseList addObject:responseModel];
    }
    
    // 计算Cell的高度
    [self calculCellheightRecalcul:YES];
}

// 计算文本所需要的高度
- (void)caculLabelWithString:(NSString *)string {
    if (string == nil || [string isEqualToString:@""]) {
        return;
    }
    CGSize textSize = [string textSizeWithtextMaxSize:CGSizeMake(kTextLabelWidth, MAXFLOAT) font:[UIFont systemFontOfSize:kTextFont]];
    
    self.textLabelHeight = textSize.height;
}
/**
 处理点赞人列表-YYLabel显示
 并计算相应的点赞高度
 */
- (void)dealLikes{
    NSString *userNameLink = @"";
    NSMutableAttributedString *allLikeListText;
    NSMutableArray *sourceArray = [NSMutableArray array];
    CGRect rect;
    
    for (NSInteger i = 0; i < self.likeList.count; i++) {
        YFMomentsPersonModel *model = self.likeList[i];
        if (i == self.likeList.count - 1) {
            userNameLink = [userNameLink stringByAppendingString:model.userName];
        }else{
            userNameLink = [userNameLink stringByAppendingString:[model.userName stringByAppendingString:@"、"]];
        }
        [sourceArray addObject:model.userName];
    }
    
    UIImage *image = [UIImage imageNamed:@"find_like_list"];
    NSMutableAttributedString *attachText= [NSMutableAttributedString attachmentStringWithContent:image contentMode:UIViewContentModeCenter attachmentSize:CGSizeMake(kTextFont, kTextFont) alignToFont:[UIFont systemFontOfSize:kTextFont] alignment:YYTextVerticalAlignmentCenter];
    allLikeListText = [[NSMutableAttributedString alloc] initWithAttributedString:attachText];
    [allLikeListText appendString:[NSString stringWithFormat:@" %@",userNameLink]];
    allLikeListText.lineSpacing = 2;
    allLikeListText.font = [UIFont boldSystemFontOfSize:kTextFont];
    rect = [allLikeListText boundingRectWithSize:CGSizeMake(kTextLabelWidth, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil];
    if ([userNameLink isEqualToString:@""]) {
        self.likeHeight = 0;
        self.likesString = nil;
    }else{
        for (NSInteger i = 0 ; i < sourceArray.count; i++) {
            NSRange range;
            NSString *preString;
            NSString *needString = sourceArray[i];
            NSArray *subArray = [sourceArray subarrayWithRange:NSMakeRange(0, i)];
            for (NSString *sub in subArray) {
                if (preString == nil) {
                    preString = sub;
                }else{
                    preString = [preString stringByAppendingString:[NSString stringWithFormat:@"、%@",sub]];
                }
            }
            NSInteger preStringLength = preString.length;
            if (preStringLength == 0) {
                range = NSMakeRange(preStringLength+2, needString.length);
            }else{
                range = NSMakeRange(preStringLength+3, needString.length);
            }
            ///点赞人的点击事件
            [allLikeListText setTextHighlightRange:range
                                             color:[UIColor colorWithHex:0x576b95]
                                   backgroundColor:[UIColor grayColor]
                                         tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
                                             [[NSNotificationCenter defaultCenter] postNotificationName:kNoticeWatchUserInfo object:nil userInfo:@{@"userID":[_likeList[i] userID]}];
                                         }];
        }
        self.likeHeight = rect.size.height+2;
        self.likesString = allLikeListText;
    }
}

// 计算图片的高度
- (CGFloat)caculImageViewHeight {
    NSInteger count = self.images.count;
    CGFloat height = 0;
    if (count == 1) {
        // 单张图
        YFMomentImageModel *imgModel = self.images[0];
        CGSize imageSize = CGSizeMake(imgModel.imageOriginWidth, imgModel.imageOriginHeight);
        if (imgModel.imageOriginWidth > imgModel.imageOriginHeight) {
            if (imgModel.isLongImage) {
                imageSize.height = (kImageMaxWidth * imageSize.height)/imageSize.width;
                imageSize.width = kImageMaxWidth;
                if (imageSize.height < kImageHMinWidth) {
                    imageSize.height = kImageHMinWidth;
                }
            }else {
                CGFloat showW = imageSize.width;// 应该显示的宽度
                if (imageSize.width < kImageMinWidth) {
                    showW = kImageMinWidth;
                }else if (imageSize.width > kImageMaxWidth){
                    showW = kImageMaxWidth * 0.8;
                }
                CGFloat ratio = (imageSize.width / showW);
                CGFloat imagWHScale = imageSize.height / imageSize.width;// 图片宽高比
                imageSize.width = imageSize.width / ratio;
                // 高按等比缩小
                imageSize.height = imageSize.width * (imagWHScale);
            }
        }else if (imgModel.imageOriginWidth < imgModel.imageOriginHeight){
            if (imgModel.isLongImage) {
                CGFloat W2 = 0.3*kImageMaxWidth;
                imageSize.height = (W2 * imageSize.height)/imageSize.width;
                imageSize.width = W2;
                if (imageSize.height > imageSize.width * 3) {
                    imageSize.height = imageSize.width * 3;
                }
            }else {
                CGFloat showH = imageSize.height;// 应该显示的宽度
                // 最大高度/ 最小高度
                if (imageSize.height < kImageMinWidth) {
                    showH = kImageMinWidth;
                }else if (imageSize.height > kImageMaxWidth * 0.8){
                    showH = kImageMaxWidth * 0.8;
                }
                CGFloat ratio = (imageSize.height / showH);
                CGFloat imagHWScale = imageSize.width / imageSize.height;// 图片高宽比
                imageSize.height = imageSize.height / ratio;
                // 高按等比缩小
                imageSize.width = imageSize.height * (imagHWScale);
            }
        }else {
            // 宽==高
            imageSize = CGSizeMake(kImageMinWidth, kImageMinWidth);
        }
        self.singleImageSize = imageSize;
        height = imageSize.height;
    }else {
        height = kImageHeight + (count / 4) * (kImageHeight + 4);
    }
    self.imagesHeight = height;
    return height;
}

/**
 计算评论需要的高度
 */
- (void)calculCommetHeight{
    self.commentHeigh = 0;
    for (YFMomentResponseModel *model in self.responseList) {
        self.commentHeigh += model.commentHeight;
    }
}

- (void)caucalOtherHeight {
    self.timeAdressHeight = self.latitude ? kValidAdressHeight:kAvalidAdressHeight;
    self.showMoreSate = ShowMoreBtnSatePackUp;
    self.isMyMoment = [self.userID isEqualToString:[User getLastUser].userInforItem.userID]?YES:NO;
}

// recalculAll :是否需要全部重新计算
- (void)calculCellheightRecalcul:(BOOL)recalculAll {
    
    if (recalculAll) {
        [self caculLabelWithString:self.text];
        [self caculImageViewHeight];
        [self dealLikes];
        [self calculCommetHeight];
        [self caucalOtherHeight];
    }
    
    NSInteger space;
    if (self.likeHeight == 0 && self.commentHeigh == 0) {
        space = 8;
    }else{
        space = 16;
    }
    if (self.textLabelHeight > kTextLabelNormalHeight) {
        ///需要显示更多
        self.isNeedShowMoreBtn = YES;
        self.normalCellHeight = kNickNameHeight + kTextLabelNormalHeight + kShowTextBtnHeight + self.imagesHeight + self.timeAdressHeight + (kBottomSpaceHeight + self.likeHeight + space + self.commentHeigh);
        self.showMoreCellHeight = kNickNameHeight + self.textLabelHeight + kShowTextBtnHeight + self.imagesHeight + self.timeAdressHeight + (kBottomSpaceHeight + self.likeHeight + space + self.commentHeigh);
    }else{
        ///无需显示更多
        self.isNeedShowMoreBtn = NO;
        self.normalCellHeight = self.showMoreCellHeight = kNickNameHeight + self.textLabelHeight + kHideTextBtnHeight + self.imagesHeight + self.timeAdressHeight + (kBottomSpaceHeight + self.likeHeight + space + self.commentHeigh);
    }
}

#pragma mark - 事件操作
/**
 点赞、取消赞
 @param         state        YES:点赞 NO:取消赞
 */
- (void)editLikeState:(BOOL)state {
    UserInforItem *userInfo = [User getLastUser].userInforItem;
    [[RLMRealm defaultRealm] beginWriteTransaction];
    if (state) {
        ///点赞
        YFMomentsPersonModel *model = [YFMomentsPersonModel momentPersonModelWithUID:userInfo.userID userName:userInfo.name];
        [self.likeList addObject:model];
    }else{
        ///取消赞
        NSInteger removeIndex = [self.likeList indexOfObjectWhere:@"userID == %@",userInfo.userID];
        [[RLMRealm defaultRealm] deleteObject:self.likeList[removeIndex]];
       // [self.likeList removeObjectAtIndex:removeIndex];
    }
    [self dealLikes];
    ///计算cell高度
    [self calculCellheightRecalcul:NO];
    [[RLMRealm defaultRealm] commitWriteTransaction];
}

/**
 添加一条评论
 @param         model        评论数据模型
 */
- (void)addCommentModel:(YFMomentResponseModel *)model {
    [[RLMRealm defaultRealm] beginWriteTransaction];
    model.momentModel = self;
    ///添加新的数据
    [self.responseList addObject:model];
    ///计算评论所需高度
    [self calculCommetHeight];
    ///计算cell高度
    [self calculCellheightRecalcul:NO];
    [[RLMRealm defaultRealm] commitWriteTransaction];
}

/**
 添加一条回复
 @param         model        回复数据模型
 */
- (void)addResponseModel:(YFMomentResponseModel *)model {
    [[RLMRealm defaultRealm] beginWriteTransaction];
    model.momentModel = self;
    ///添加新的数据
    [self.responseList addObject:model];
    ///计算评论所需高度
    [self calculCommetHeight];
    ///计算cell高度
    [self calculCellheightRecalcul:NO];
    [[RLMRealm defaultRealm] commitWriteTransaction];
}

@end
